package com.augurit.gzcgwsp.ywcmn.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.gzcgwsp.ywcmn.convert.YwComSjclConvertor;
import com.augurit.gzcgwsp.ywcmn.dao.YwComAjClDao;
import com.augurit.gzcgwsp.ywcmn.dao.YwComSjclDao;
import com.augurit.gzcgwsp.ywcmn.dao.YwComSjcllistDao;
import com.augurit.gzcgwsp.ywcmn.dao.YwComSjcllistOtherDao;
import com.augurit.gzcgwsp.ywcmn.entity.YwComAjCl;
import com.augurit.gzcgwsp.ywcmn.entity.YwComSjcl;
import com.augurit.gzcgwsp.ywcmn.entity.YwComSjcllist;
import com.augurit.gzcgwsp.ywcmn.entity.YwComSjcllistOther;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm;

@Service
@Transactional
public class YwComSjclServiceImpl implements IYwComSjclService{

	@Autowired
	private YwComSjclDao ywComSjclDao;
	
	@Autowired
	private YwComAjClDao ajclDao;
	
	@Autowired
	private YwComSjcllistDao ywComSjcllistDao;
	
	@Autowired
	private YwComSjcllistOtherDao ywComSjcllistOtherDao;
	
	@Transactional(readOnly = true)
	public YwComSjclForm get(Long id) {
		YwComSjcl entity = ywComSjclDao.get(id);
		return YwComSjclConvertor.convertVoToForm(entity);
	}
	
	public void changeChxstate(YwComSjclForm form,String otherFlag) {
	    try {
	        String findsql = "from YwComAjCl where ajid=" + form.getAjid() + " and clid=" + form.getId() + " and tplcode='" + form.getTplcode() + "'";
             YwComAjCl ajentity = (YwComAjCl) ajclDao.createQuery(findsql).uniqueResult();
	        if (form.getId() != null) {
        	    YwComSjcl sjclEntity = ywComSjclDao.getEntity(form.getId());
        	    if (sjclEntity == null) {
        	        sjclEntity = new YwComSjcl();
        	        sjclEntity.setTplid(form.getTplid());
        	        ywComSjclDao.save(sjclEntity);
        	          if (ajentity == null) {
        	              ajentity = new YwComAjCl();
                          ajentity.setAjid(form.getAjid());
                          ajentity.setClid(form.getId());
                          ajentity.setTplcode(form.getTplcode());
                          ajentity.setSfdz(form.getSfdz());
                      } else {
                          ajentity.setSfdz(form.getSfdz());
                      }
                      ajclDao.save(ajentity);
        	    }else{
        	        if(sjclEntity.getId()!=null){
        	            String filepath=sjclEntity.getFilepath();
        	            if(StringUtils.isNotBlank(filepath)){
        	                File file=new File(filepath);
                            if(file.exists()){
                                file.delete();
                            }
        	            }
        	            sjclEntity.setFilepath(null);
                        sjclEntity.setFilename(null);
                        sjclEntity.setFkid(null);
                        sjclEntity.setTplid(null);
                        ywComSjclDao.save(sjclEntity);
                        if(ajentity!=null){
                            ajclDao.delete(ajentity);
                        }
        	        }
        	        
        	    }
        	     //修改收件材料附件
        	    if("Y".equals(otherFlag)){
        	    	updateYwComSjcllistOther(form);
        	    }else{
        	    	updateYwComSjcllist(form);
        	    }
	        } else {
	            YwComSjcl sjclEntity = new YwComSjcl();
                sjclEntity.setTplid(form.getTplid());
                sjclEntity.setFkid(form.getFkid());
                //sjclEntity.setVerion("1");
                ywComSjclDao.save(sjclEntity);
                
	            YwComAjCl entity = new YwComAjCl();
                entity.setClid(sjclEntity.getId());
                entity.setAjid(form.getAjid());
                entity.setTplcode(form.getTplcode());
                entity.setSfdz(form.getSfdz());
                ajclDao.save(entity);
                
                //修改收件材料附件
                if("Y".equals(otherFlag)){
        	    	updateYwComSjcllistOther(form);
        	    }else{
        	    	updateYwComSjcllist(form);
        	    }
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	public void updateYwComSjcllist(YwComSjclForm form){
		String sjclsql = "from YwComSjcllist  where  id='"+form.getTplid()+"'";
		 List<YwComSjcllist> list= ywComSjcllistDao.find(sjclsql);
		 YwComSjcllist entitylist=list.get(0);
		 if(entitylist!=null){
			 entitylist.setSfdz("1");
   		 ywComSjcllistDao.save(entitylist);
		 }
	}
	
	public void updateYwComSjcllistOther(YwComSjclForm form){
		String sjclsql = "from YwComSjcllistOther  where  id='"+form.getTplid()+"'";
		 List<YwComSjcllistOther> list= ywComSjcllistOtherDao.find(sjclsql);
		 YwComSjcllistOther entitylistOther=list.get(0);
		 if(entitylistOther!=null){
			 entitylistOther.setSfdz("1");
   		 ywComSjcllistOtherDao.save(entitylistOther);
		 }
	}
	
	public List<YwComSjclForm> getList(String templateCode, Long ajid, String sjclTplName) {
        StringBuffer hql = new StringBuffer("select ps.* from Yw_Com_Sjcl ps, Yw_Com_Aj_Cl cl, YW_COM_SJCLLIST cs where ps.id=cl.clid and ps.tplid=cs.id and cl.ajid = " + ajid + " and cl.tplcode='" + templateCode + "' and cs.title like '%"+sjclTplName+"%'");
        List<YwComSjcl> objs = ywComSjclDao.getSession().createSQLQuery(hql.toString()).addEntity(YwComSjcl.class).list();
        if (objs == null || objs.size() == 0) return new ArrayList<YwComSjclForm>();
       
        List<YwComSjclForm> formList = new ArrayList<YwComSjclForm>();
        for (YwComSjcl obj : objs) {
            YwComSjclForm sjclForm = obj == null ? new YwComSjclForm() : YwComSjclConvertor.convertVoToForm(obj);
            formList.add(sjclForm);
        }
        return formList;
    }
	
    public List<YwComSjclForm> getList(YwComSjclForm form) {
        StringBuffer hql = new StringBuffer("select ps.*, cl.sfdz from Yw_Com_Sjcl ps, Yw_Com_Aj_Cl cl where cl.ajid = " + form.getAjid() + " and cl.tplcode='" + form.getTplcode() + "' and cl.clid=ps.id(+)");
        List<Object[]> objs = ywComSjclDao.getSession().createSQLQuery(hql.toString()).addEntity(YwComSjcl.class).addScalar("sfdz").list();
        if (objs == null || objs.size() == 0) return new ArrayList<YwComSjclForm>();
        List<YwComSjclForm> formList = new ArrayList<YwComSjclForm>();
        for (Object[] obj : objs) {
            YwComSjcl entity = (YwComSjcl) obj[0];
            YwComSjclForm sjclForm = entity == null ? new YwComSjclForm() : YwComSjclConvertor.convertVoToForm(entity);
            sjclForm.setSfdz((String) obj[1]);
            boolean hasExisted = false;
            for (YwComSjclForm iform : formList) {
                if(iform.getTplid()!=null && sjclForm.getTplid()!=null){
                    if (iform.getTplid().longValue() == sjclForm.getTplid().longValue()) {
                        String filepath=sjclForm.getFilepath();
                        if(StringUtils.isNotBlank(filepath)){
                        	//File file=new File(contextpath+filepath);
                            //if(file.exists()){
                                iform.setFilename(iform.getFilename() + "," + sjclForm.getFilename());
                                iform.setFilepath(iform.getFilepath() + "," + sjclForm.getFilepath());
                                iform.setFiletype(iform.getFiletype() + "," + sjclForm.getFiletype());
                                hasExisted = true;
                                break;
                        //} 
                      }
                    }
                }
                
            }
            if (!hasExisted) formList.add(sjclForm);
        }
        return formList;
    }
    /**
     * 其他的
     * @param form
     * @return
     */
    public List<YwComSjclForm> getOtherList(YwComSjclForm form) {
        StringBuffer hql = new StringBuffer("select ps.*, cl.sfdz from Yw_Com_Sjcl ps, Yw_Com_Aj_Cl cl where cl.ajid = " + form.getAjid() + " and cl.tplcode='" + form.getTplcode() + "' and cl.clid=ps.id(+)");
        List<Object[]> objs = ywComSjclDao.getSession().createSQLQuery(hql.toString()).addEntity(YwComSjcl.class).addScalar("sfdz").list();
        if (objs == null || objs.size() == 0) return new ArrayList<YwComSjclForm>();
        List<YwComSjclForm> formList = new ArrayList<YwComSjclForm>();
        for (Object[] obj : objs) {
            YwComSjcl entity = (YwComSjcl) obj[0];
            YwComSjclForm sjclForm = entity == null ? new YwComSjclForm() : YwComSjclConvertor.convertVoToForm(entity);
            sjclForm.setSfdz((String) obj[1]);
            boolean hasExisted = false;
            for (YwComSjclForm iform : formList) {
                if(iform.getTplidOther()!=null && sjclForm.getTplidOther()!=null){
                    if (iform.getTplidOther().longValue() == sjclForm.getTplidOther().longValue()) {
                        String filepath=sjclForm.getFilepath();
                        if(StringUtils.isNotBlank(filepath)){
                        	//File file=new File(contextpath+filepath);
                            //if(file.exists()){
                                iform.setFilename(iform.getFilename() + "," + sjclForm.getFilename());
                                iform.setFilepath(iform.getFilepath() + "," + sjclForm.getFilepath());
                                iform.setFiletype(iform.getFiletype() + "," + sjclForm.getFiletype());
                                hasExisted = true;
                                break;
                        //} 
                      }
                    }
                }
                
            }
            if (!hasExisted) formList.add(sjclForm);
        }
        return formList;
    }
    
    /**
     * 通过ajid、tplcode、tplid查询该案件的该附件上传的所有列表
     */
    public List<YwComSjclForm> getFjList(Long ajid,Long tplid,String tplcode) {
        StringBuffer hql = new StringBuffer("select ps.*, cl.sfdz from Yw_Com_Sjcl ps, Yw_Com_Aj_Cl cl where cl.ajid = " + ajid + " and cl.tplcode='" + tplcode + "' and cl.clid=ps.id(+) and ps.tplid='"+tplid+"'");
        List<Object[]> objs = ywComSjclDao.getSession().createSQLQuery(hql.toString()).addEntity(YwComSjcl.class).addScalar("sfdz").list();
        if (objs == null || objs.size() == 0) return new ArrayList<YwComSjclForm>();
        List<YwComSjclForm> formList = new ArrayList<YwComSjclForm>();
        for (Object[] obj : objs) {
            YwComSjcl entity = (YwComSjcl) obj[0];
            YwComSjclForm sjclForm = entity == null ? new YwComSjclForm() : YwComSjclConvertor.convertVoToForm(entity);
            formList.add(sjclForm);
        }
        return formList;
    }
    
    public void updateByNewForm(Long ajid) {
        String sql = "update Yw_Com_Aj_Cl set ajid=" + ajid + " where ajid=0";
        ajclDao.getSession().createSQLQuery(sql).executeUpdate();
    }
    
    public void saveSjclBySelectQyxx(YwComSjclForm form) {
        String sql = "delete from Yw_Com_Aj_Cl where ajid=" + form.getAjid();
        ajclDao.getSession().createSQLQuery(sql).executeUpdate();
        
        List<YwComSjclForm> sjclList = this.loadQySjclList(form);
        
        for (YwComSjclForm sjclForm : sjclList) {
            YwComAjCl entity = new YwComAjCl();
            entity.setAjid(form.getAjid());
            entity.setClid(sjclForm.getId());
            entity.setTplcode(form.getTplcode());
            ajclDao.save(entity);
        }
    }
    
    public List<YwComSjclForm> loadQySjclList(YwComSjclForm form) {
        StringBuffer hql = new StringBuffer();
        hql.append("from YwComSjcl ps where ps.fkid=" + form.getFkid() + " and ps.version='1'");
        
        List<YwComSjcl> entityList = ywComSjclDao.find(hql.toString());
        if (entityList == null || entityList.size() == 0) return new ArrayList<YwComSjclForm>();

        List<YwComSjclForm> formList = new ArrayList<YwComSjclForm>();
        for (YwComSjcl entity : entityList) {
            YwComSjclForm sjclForm = YwComSjclConvertor.convertVoToForm(entity);
            formList.add(sjclForm);
        }
        return formList;
    }
	
	public void delete(Long... ids) {
		ywComSjclDao.delete(ids);
	}

	public void save(YwComSjclForm... forms) {
		if(forms != null)
			for(YwComSjclForm form : forms)
				this.save(form);
	}
	
    public void saveOtherByUpload(YwComSjclForm form) {
        if (form == null) return;

        String delselSql = "from YwComSjcl cl where cl.fkid=" + form.getFkid() + " and cl.tplidOther=" + form.getTplid() + " and cl.filepath is null";
        List<YwComSjcl> entityList = ywComSjclDao.find(delselSql);
        for (YwComSjcl delEntity : entityList) {
            String del0sql = "delete from Yw_Com_Aj_Cl ajcl where ajcl.clid=" + delEntity.getId();
            ywComSjclDao.getSession().createSQLQuery(del0sql).executeUpdate();
            ywComSjclDao.delete(delEntity);
        }
        
        String updateVersion0Sql = "update Yw_Com_Sjcl cl set cl.version = '0' where cl.fkid=" + form.getFkid() + " and cl.tplid_other=" + form.getTplid();
        ywComSjclDao.getSession().createSQLQuery(updateVersion0Sql).executeUpdate();
        
        form.setVersion("1");
        this.save(form);

        YwComAjCl ajclEntity = new YwComAjCl();
        
        ajclEntity.setAjid(form.getAjid());
        ajclEntity.setClid(form.getId());
        ajclEntity.setTplcode(form.getTplcode());
        
        ajclDao.save(ajclEntity);
        
        String updateVersion1Sql = "update Yw_Com_Sjcl cl set cl.version = '1' where cl.fkid=" + form.getFkid() + " and cl.tplid_other=" + form.getTplid();
        ywComSjclDao.getSession().createSQLQuery(updateVersion1Sql).executeUpdate();
        //修改收件材料附件
        String sjclsql = "from YwComSjcllistOther  where  id='"+form.getTplid()+"'";
		 List<YwComSjcllistOther> list= ywComSjcllistOtherDao.find(sjclsql);
		 YwComSjcllistOther entity=list.get(0);
		 entity.setSfdz("0");
		 ywComSjcllistOtherDao.save(entity);
        /*String sql = "select ajcl.id from Yw_Com_Aj_Cl ajcl, Yw_Com_Sjcl cl where ajcl.ajid=" + form.getAjid() + " and ajcl.clid=cl.id and cl.tplid=" + form.getTplid();
        
        List<Long> dataList = ywComSjclDao.getSession().createSQLQuery(sql).addScalar("id", Hibernate.LONG).list();
        
        if (dataList != null && dataList.size() != 0) {
            ajclDao.delete(dataList.toArray(new Long[dataList.size()]));
        }*/
        
    }
    
    public void saveByUpload(YwComSjclForm form) {
        if (form == null) return;

        String delselSql = "from YwComSjcl cl where cl.fkid=" + form.getFkid() + " and cl.tplid=" + form.getTplid() + " and cl.filepath is null";
        List<YwComSjcl> entityList = ywComSjclDao.find(delselSql);
        for (YwComSjcl delEntity : entityList) {
            String del0sql = "delete from Yw_Com_Aj_Cl ajcl where ajcl.clid=" + delEntity.getId();
            ywComSjclDao.getSession().createSQLQuery(del0sql).executeUpdate();
            ywComSjclDao.delete(delEntity);
        }
        
        String updateVersion0Sql = "update Yw_Com_Sjcl cl set cl.version = '0' where cl.fkid=" + form.getFkid() + " and cl.tplid=" + form.getTplid();
        ywComSjclDao.getSession().createSQLQuery(updateVersion0Sql).executeUpdate();
        
        form.setVersion("1");
        this.save(form);

        YwComAjCl ajclEntity = new YwComAjCl();
        
        ajclEntity.setAjid(form.getAjid());
        ajclEntity.setClid(form.getId());
        ajclEntity.setTplcode(form.getTplcode());
        
        ajclDao.save(ajclEntity);
        
        String updateVersion1Sql = "update Yw_Com_Sjcl cl set cl.version = '1' where cl.fkid=" + form.getFkid() + " and cl.tplid=" + form.getTplid();
        ywComSjclDao.getSession().createSQLQuery(updateVersion1Sql).executeUpdate();
        //修改收件材料附件
        String sjclsql = "from YwComSjcllist  where  id='"+form.getTplid()+"'";
		 List<YwComSjcllist> list= ywComSjcllistDao.find(sjclsql);
		 YwComSjcllist entity=list.get(0);
		 entity.setSfdz("0");
		 ywComSjcllistDao.save(entity);
        /*String sql = "select ajcl.id from Yw_Com_Aj_Cl ajcl, Yw_Com_Sjcl cl where ajcl.ajid=" + form.getAjid() + " and ajcl.clid=cl.id and cl.tplid=" + form.getTplid();
        
        List<Long> dataList = ywComSjclDao.getSession().createSQLQuery(sql).addScalar("id", Hibernate.LONG).list();
        
        if (dataList != null && dataList.size() != 0) {
            ajclDao.delete(dataList.toArray(new Long[dataList.size()]));
        }*/
        
    }
	
	public void save(YwComSjclForm form){
		if(form != null){
			YwComSjcl entity = null;
			
			if(form != null && form.getId() != null){
				entity = ywComSjclDao.get(form.getId());
			}else{
				entity = new YwComSjcl();
			}
			
			YwComSjclConvertor.convertFormToVo(form, entity);
			
			ywComSjclDao.save(entity);
			
			form.setId(entity.getId());
		}
	}

	@Transactional(readOnly = true)
	public Page<YwComSjclForm> search(Page<YwComSjclForm> page, YwComSjclForm form) {
		Page pg = PageUtils.newPageInstance(page);
		
		StringBuffer hql = new StringBuffer("from YwComSjcl ps where 1=1");
		List values = new ArrayList();
		
		if(form != null){
			
		}
		
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		ywComSjclDao.findPage(pg, hql.toString(), values);
		
		List<YwComSjclForm> list = YwComSjclConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	@Transactional(readOnly = true)
	public Page<YwComSjclForm> search(Page<YwComSjclForm> page, List<PropertyFilter> filters) {
		Page<YwComSjcl> pg = PageUtils.newPageInstance(page);
		
		ywComSjclDao.findPage(pg, filters);
		
		List<YwComSjclForm> list = YwComSjclConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

    public List<YwComSjcl> getFormByAjId(Long ajId,Long tempId) {
        String ajsql="select t.clid from "+YwComAjCl.class.getName()+" t where t.ajid='"+ajId+"'";
        List<Long> clids = ywComSjclDao.find(ajsql);
        String ids="";
        for(long clid:clids){
            ids+=clid+",";
        }
        if(ids.length()>0){
            ids=ids.substring(0,ids.length()-1);
        }
        if(StringUtils.isNotBlank(ids)){
            String sjclsql = "from YwComSjcl cl where cl.id in("+ids+")"+" and cl.tplid='"+tempId+"'";
            return ywComSjclDao.find(sjclsql);
        }else{
            return null;
        }
       
    }

    /*
     * (non-Javadoc)
     * @see com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService#updateAttach(com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm)
     */
	public void updateAttach(YwComSjclForm paramForm) {
		String sjclsql = "from YwComSjcllist  where  id='"+paramForm.getTplid()+"'";
		 List<YwComSjcllist> list= ywComSjcllistDao.find(sjclsql);
		 YwComSjcllist entity=list.get(0);
		 if(StringUtils.isNotBlank(paramForm.getFyjs())){
			 entity.setFyjs(Long.valueOf(paramForm.getFyjs()));
		 }
		 if(StringUtils.isNotBlank(paramForm.getFyjs())){
			 entity.setYjs(Long.valueOf(paramForm.getFyjs()));
		 }
		 
		 entity.setSfdz(null);
		 ywComSjcllistDao.save(entity);
	}
	
	public void updateOtherAttach(YwComSjclForm paramForm) {
		String sjclsql = "from YwComSjcllistOther  where  id='"+paramForm.getTplid()+"'";
		 List<YwComSjcllistOther> list= ywComSjcllistOtherDao.find(sjclsql);
		 YwComSjcllistOther entity=list.get(0);
		 if(StringUtils.isNotBlank(paramForm.getFyjs())){
			 entity.setFyjs(Long.valueOf(paramForm.getFyjs()));
		 }
		 if(StringUtils.isNotBlank(paramForm.getFyjs())){
			 entity.setYjs(Long.valueOf(paramForm.getFyjs()));
		 }
		 
		 entity.setSfdz(null);
		 ywComSjcllistOtherDao.save(entity);
	}
	
	/**
	 * 保存列表增加的其他材料
	 * @param form
	 */
	public void saveOther(YwComSjclForm form) {
		YwComSjcllistOther entity = new YwComSjcllistOther();
		entity.setAjid(form.getAjid());
		entity.setYjs(Long.parseLong(form.getYjs()));
		entity.setFyjs(Long.parseLong(form.getFyjs()));
		entity.setTplcode(form.getTplcode());
		entity.setTitle(form.getOtherName());
		entity.setSfdz("0");
		ywComSjcllistOtherDao.save(entity);
	}

}
